package com.njtoyo.taxi.admin.service.business.notify.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.njtoyo.taxi.admin.mapper.master.entity.AppCustomerNotify;
import com.njtoyo.taxi.admin.mapper.master.mapper.AppCustomerNotifyMapper;
import com.njtoyo.taxi.admin.service.business.notify.AppCustomerNotifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class AppCustomerNotifyServiceImpl implements AppCustomerNotifyService {
    @Autowired
    private AppCustomerNotifyMapper appCustomerNotifyMapper;

    public static final List<String> path = Arrays.asList("index", "menu", "wallet");
    public static final List<String> style = Arrays.asList("reddot", "reddot", "reddot");
    public static final List<String> styleContent = Arrays.asList("", "", "");

    @Transactional
    public void updateCustomerNotifyForCoupon(List<Long> userIds) {
        for (Long userId : userIds) {
            // 判断是否存在
            AppCustomerNotify one = new LambdaQueryChainWrapper<>(appCustomerNotifyMapper)
                    .eq(AppCustomerNotify::getCustomerId, userId)
                    .eq(AppCustomerNotify::getPath, JSONUtil.toJsonStr(path))
                    .orderByDesc(AppCustomerNotify::getId)
                    .last("limit 1")
                    .one();

            if (Objects.isNull(one)) {
                // 插入
                AppCustomerNotify insertItem = new AppCustomerNotify();
                insertItem.setCustomerId(userId);
                insertItem.setPath(JSONUtil.toJsonStr(path));

                insertItem.setIsRead(false);
                insertItem.setStyle(JSONUtil.toJsonStr(style));
                insertItem.setStyleContent(JSONUtil.toJsonStr(styleContent));

                appCustomerNotifyMapper.insert(insertItem);
            } else {
                // 更新
                one.setIsRead(false);
                one.setStyle(JSONUtil.toJsonStr(style));
                one.setStyleContent(JSONUtil.toJsonStr(styleContent));

                one.setCreatedAt(null);
                one.setUpdatedAt(new Date());

                appCustomerNotifyMapper.updateById(one);
            }
        }
    }
}
